#!/usr/bin/perl -w

# Parses PNGs into their component chunks,
# and shows them as calls to the data-demo API.

use strict;

my $png = $ARGV[0];
die "requires png file.\n" unless $png;
open(PNG,$png) or die "Couldn't open $png: $!\n";
binmode PNG;

my $header;
read(PNG, $header, 8);
unless ($header eq "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a") {
  die "not png header: ".bytes($header);
}

my $type="";

while ($type ne "IEND") {
  print "+ " if $type;
  my ($size, $data, $crc_string, $crc, $array_string);
  my $buffer;
  read(PNG, $buffer, 8);
  ($size, $type) = unpack("N A4",$buffer);
  read(PNG, $data, $size);
  read(PNG, $crc_string, 4);
  
  $array_string = bytes($data);
  $crc = unpack("N",$crc_string);
  
  print "new my.Png.Chunk('$type', $array_string) // CRC: $crc\n";
}
  

sub bytes {
  my $data = shift;
  my @bytes = split(//, $data);
  my $i = 0;
  return 
    "[" . 
    join(",",map { $i++; (($i%40) ? "" : "\n") . ord($_) . (/[A-Z]/i ? " /* $_ */" : "") } @bytes) .
    "] /* " .
    scalar(@bytes).
    " bytes */"
}